//
//  DMDingDanGuanLiViewController.m
//  DMGME
//
//  Created by MC on 15/11/3.
//  Copyright © 2015年 GYP. All rights reserved.
//

#import "DMDingDanGuanLiViewController.h"
#import "DMErWeiMaViewController.h"
#import "OrderDetaiABlViewCell.h"
#import "OrderABModel.h"
#import "OrderGoodsModel.h"
#import "footerView.h"
#import "headerView.h"
#import "DMCustomViewController.h"
#import "SearchViewController.h"
#import "MJRefresh.h"
@interface DMDingDanGuanLiViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
    UIView *_bigView;
    UITableView *_tableView;
    headerView *_hview;
    NSString *str;
    NSString *t;
    NSString *h;
    NSString *fen;
    NSString *miao;
    NSTimer *timer;
    int seconds;
    UILabel *lableTime;
    long int _section;
    NSString *_mId;
    NSString *_is;
    UIPickerView *pickerViewa;
}
@property (nonatomic,strong) NSArray *btntitle;
@property (nonatomic,strong) NSMutableArray *btnArr;
@property (nonatomic,strong) NSMutableArray *datas;
@property (nonatomic,strong) UILabel *tishiLabel;
@end

@implementation DMDingDanGuanLiViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_tableView) {
        
        [_tableView reloadData];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"订单管理";
    [self AddLeftImageBtn:[UIImage imageNamed:@"fanhui_03 2"]target:self action:@selector(GoBack)];
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem * rightButton = [[UIBarButtonItem alloc]
                                     initWithTitle:@""
                                     style:UIBarButtonItemStyleBordered
                                     target:self
                                     action:@selector(rightBtn)];
    rightButton.image=[UIImage imageNamed:@"ScanButton"];
    rightButton.tintColor=[UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightButton;
    _datas = [NSMutableArray array];
    [self tableViewHeaderView];
    [self createTableView];
  
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethodss) userInfo:nil repeats:YES];
    
}
-(void)timerMethodss
{
    if (_YesOrNo == 2) {
        [_tableView reloadData];
    }
    
}
-(void)setYesOrNo:(int)YesOrNo
{
    _YesOrNo = YesOrNo;
}
-(void)createTableView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, KHeight/4, KWidth, KHeight/4*3-64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[OrderDetaiABlViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    [_tableView headerBeginRefreshing];
    //添加下拉和上拉事件
    [_tableView addHeaderWithTarget:self action:@selector(downlaodData1)];
    
    _tishiLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, _tableView.frame.origin.x+20, KWidth-200, 20)];
    _tishiLabel.textAlignment = NSTextAlignmentCenter;
    _tishiLabel.font = [UIFont systemFontOfSize:12];
    _tishiLabel.textColor = [UIColor grayColor];
    _tishiLabel.text = @"目前暂无数据";
    _tishiLabel.hidden = YES;
    [_tableView addSubview:_tishiLabel];
}
-(void)downlaodData1
{
    if (self.YesOrNo == 0) {
        
        [self downLoadData:@"toBeConfirmed"];
    }
    else if (self.YesOrNo == 1)
    {
        [self downLoadData:@"toBePickup"];
    }else if (self.YesOrNo == 2)
    {
        [self downLoadData:@"delivered"];
    }else if (self.YesOrNo == 3)
    {
        [self downLoadData:@"refund"];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    OrderABModel * model = [_datas  objectAtIndex:section];
    return model.goodsArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 130;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"cell";
    
    OrderDetaiABlViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    OrderABModel * abModel = [_datas objectAtIndex:indexPath.section ];
    OrderGoodsModel *mode = [[abModel goodsArray] objectAtIndex:indexPath.row];
    
    cell.subModel = mode;
     _mId = [abModel id];

//     NSLog(@"cell_mId == %@ == %ld == %@",_mId,_section,abModel.order_sn);
       _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.datas.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
     _hview = [[headerView alloc]initWithFrame:CGRectMake(0, 0, KWidth, 44)];
    _hview.tag = section + 200;
    _hview.titleLabel.textColor = ComColor;
    _hview.titleLabel.font = [UIFont systemFontOfSize:13];
    _hview.backgroundColor =  self.view.backgroundColor;
    OrderABModel * model = [self.datas objectAtIndex:section];

    if(self.YesOrNo == 3){
        //待收货
        _hview.styelLable.text = @"在线支付";
        
        if ([model.status  isEqual: @"5"]) {
            _hview.titleLabel .text = [NSString stringWithFormat:@"退单已提交"];
        }
        if ([model.status  isEqual: @"6"]) {
           _hview.titleLabel.text = [NSString stringWithFormat:@"退单完成"];
        }
       
        _section = section;
    }
    else if (self.YesOrNo == 2)
    {
        //待发货
        _hview.styelLable.text = @"在线支付";
        _section = section;
        if(model.status.intValue == 4||model.finish_time.longLongValue - [[NSDate date] timeIntervalSince1970]  <=0 )
        {
            _hview.titleLabel.text = [NSString stringWithFormat:@"订单已完成"];
        }
        if(model.status.intValue == 3 )
        {
            
            [_hview.titleLabel setText:[NSString stringWithFormat:@"等待用户确认:"]];
            _hview.tag = 300;
        }
        [self timerMethod:nil];
//         NSLog(@"model.status=== %@",model.status);
    }
    else if (self.YesOrNo == 1)
    {
        _hview.titleLabel.text = @"等待取货";
       
           }
    else
    {
        _hview.titleLabel.text = @"等待确认";

    }
    return _hview;

}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    OrderABModel * model = [self.datas objectAtIndex:section];
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 90)];
    footView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *headerLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 22, KWidth, 1)];
    
    headerLine.backgroundColor = [UIColor lightGrayColor];
    headerLine.alpha = 0.5;
    [footView addSubview:headerLine];
    
    UILabel *total = [[UILabel alloc] initWithFrame:CGRectMake(KWidth-70, 0, 70, 21)];
  
    total.textColor = [UIColor grayColor];
    total.font = [UIFont systemFontOfSize:14];
//    CGFloat fl = model.all_total.floatValue +model.coupon.floatValue;
    total.text = [NSString stringWithFormat:@"￥%@",model.all_total];
    
    [footView addSubview:total];
    
    
    NSString *string1 = [[self timeStamaps:model.get_starttime] substringToIndex:16];
    NSString *string2 = [[self timeStamaps:model.get_finishtime] substringWithRange:NSMakeRange(11, 5)];
    NSArray *textLabeArr = @[[NSString stringWithFormat:@"订单生成时间:%@",[self timeStamaps:model.order_time]],[NSString stringWithFormat:@"取货时间:%@",[NSString stringWithFormat:@"%@~%@",string1,string2]],[NSString stringWithFormat:@"订单号:%@",model.order_sn]];
    
    for (int i=0; i<3; i++) {
        UILabel *labe = [[UILabel alloc] initWithFrame:CGRectMake(12, 21*i+27, 230, 21)];
        labe.text = textLabeArr[i];
        labe.font = [UIFont systemFontOfSize:14];
        labe.textColor = [UIColor lightGrayColor];
        [footView addSubview:labe];
        
    }
    if (self.YesOrNo == 1 ||self.YesOrNo == 0) {
        NSArray *buttArr = [NSArray array];
        if (self.YesOrNo == 0) {
            buttArr = @[ @"delayButton.png",@"contactButton.png",@"confirmGoodsButton Copy"];
        }else
        {
            
            buttArr = @[ @"delayButton.png",@"contactButton.png",@"sendGoodsButton@2x"];
        }
    
    
    for (int i= 0; i<buttArr.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];

         button.frame = CGRectMake(KWidth/3+10 + (KWidth/6+15) * i,footView.frame.size.height+5, KWidth/6+10, 31);
        [button setBackgroundImage:[UIImage imageNamed:buttArr[i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonWithClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 500+section;
        [footView addSubview:button];
    }
        }
    if (self.YesOrNo == 2) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(KWidth-KWidth/6-20, footView.frame.size.height+5, KWidth/6+10, 31);
        [button setBackgroundImage:[UIImage imageNamed:@"contactButton.png"] forState:UIControlStateNormal];
         [button addTarget:self action:@selector(customWithClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 500+section;
        [footView addSubview:button];
    }
    if (self.YesOrNo == 3) {
        UILabel *hotLine = [[UILabel alloc] initWithFrame:CGRectMake(KWidth-KWidth/6-120, footView.frame.size.height+5,  KWidth/6+10, 31)];
        hotLine.font = [UIFont systemFontOfSize:13];
        hotLine.text = @"联系客服:";
        hotLine.textColor = ComColor;
        [footView addSubview:hotLine];
        
        UIButton *hotBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        hotBtn.frame = CGRectMake(KWidth-KWidth/6-60, footView.frame.size.height+5, KWidth/6+40, 31);
        [hotBtn setTitle:@"0519-8813238" forState:UIControlStateNormal];
        [hotBtn setTintColor:ComColor];
        hotBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [hotBtn addTarget:self action:@selector(hotLineClick) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:hotBtn];
    }
    return footView;
}
-(void)customWithClick:(UIButton *)sender
{
    OrderABModel * abmodel =[_datas objectAtIndex:(sender.tag-500)];

    NSString *targetId = [abmodel umobile];
    NSString *userName = [abmodel unickname];
    NSString *imgStr = [abmodel uavatar];
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    [de setObject:[abmodel umobile] forKey:@"targetId"];
    [de setObject:[abmodel unickname] forKey:@"useName"];
    [de setObject:[abmodel uavatar] forKey:@"imgStr"];
    
//    NSLog(@"[abmodel umobile]  ==%@ ,[abmodel unickname] === %@,[abmodel uavatar] == %@",[abmodel umobile],[abmodel unickname],[abmodel uavatar]);
    [de synchronize];

//    NSLog(@"===%@ === %@ ===%@",targetId,userName,imgStr);
    DMCustomViewController *custom = [[DMCustomViewController alloc] init];
    custom.targetId = targetId;
    custom.userName = userName;
    custom.titleStr = userName;   
    
    [self.navigationController pushViewController:custom animated:YES];

}
-(void)hotLineClick
{
    UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定拨打客服电话" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    al.tag = 900;
    [al show];
}
-(void)buttonWithClick:(UIButton *)sender
{

//    NSLog(@"%@_____",[NSValue valueWithCGRect:sender.frame]);
//    =    i;
//    NSLog(@"%d______",(int)((sender.frame.origin.x - KWidth/3+10)/ (KWidth/6+15)));
    int i = (int)((sender.frame.origin.x - KWidth/3+10)/ (KWidth/6+15));
    
     OrderABModel * abmodel =[_datas objectAtIndex:(sender.tag-500)];
    
//    NSLog(@"%@++++",abmodel.id);

    if (i == 0) {
         [self createTimeData];
        //获取当前的主window
        UIWindow *keyWin = [UIApplication sharedApplication].keyWindow;
        //创建背景button 点击该button 删除主window 上的所有控件
        UIButton *bgViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
        bgViewButton.frame =  keyWin.bounds;
        bgViewButton.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
        [bgViewButton addTarget:self action:@selector(cancelbgViewClick) forControlEvents:UIControlEventTouchUpInside];
        bgViewButton.tag = 1000;
        bgViewButton.alpha = 0.4;
        [keyWin addSubview:bgViewButton];
        
        UIView *dateBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 64+(KHeight-64-260)/2, KWidth, 260)];
        dateBgView.backgroundColor = [UIColor whiteColor];
        dateBgView.tag = 1001;
        [keyWin addSubview:dateBgView];
       
        //创建取消和完成按钮
        NSArray *tittleArray = @[@"取消",@"完成"];
        
        for (int i = 0; i < 2; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(i*(KWidth-54), 0, 54, 44);
            [button setTitle: tittleArray[i] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithRed:0.9 green:0.32 blue:0.32 alpha:1] forState:UIControlStateNormal];
            if (i == 0) {
                 [button addTarget:self action:@selector(ensureOrCancelClick1:) forControlEvents:UIControlEventTouchUpInside];
            }
           else
           {
                [button addTarget:self action:@selector(ensureOrCancelClick22:) forControlEvents:UIControlEventTouchUpInside];
               button.tag = abmodel.id.intValue;
           }
            
            [dateBgView addSubview:button];
        }
        
        UIImageView *lineImage = [[UIImageView alloc]initWithFrame: CGRectMake(0,43,KWidth, 0.5)];
        lineImage.alpha = 0.5;
        lineImage.image = [UIImage imageNamed:@"80"];
        [dateBgView addSubview:lineImage];
        
        //创建日期选择器
        pickerViewa = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, KWidth, 216)];
        pickerViewa.backgroundColor = [UIColor whiteColor];
        pickerViewa.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;
        pickerViewa.delegate = self;
        pickerViewa.dataSource = self;
        pickerViewa.tag = 1002;
        
        [pickerViewa selectRow:mSelectedDateIndex inComponent:0 animated:YES];
        [pickerViewa selectRow:mSelectedhourIndex inComponent:1 animated:YES];
        
        [dateBgView addSubview:pickerViewa];
        
       
    }
    if (i == 1 ) {
//        NSLog(@"501");
        
        NSString *targetId = [abmodel umobile];
        NSString *userName = [abmodel unickname];
        NSString *imgStr = [abmodel uavatar];
//        NSLog(@"===%@ === %@ ===%@",targetId,userName,imgStr);
        DMCustomViewController *custom = [[DMCustomViewController alloc] init];
        custom.targetId = targetId;
        custom.userName = userName;
        custom.titleStr = userName;
        NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
        [de setObject:targetId forKey:@"targetId"];
        [de setObject:userName forKey:@"useName"];
        [de setObject:imgStr forKey:@"imgStr"];
        [de synchronize];
        
        [self.navigationController pushViewController:custom animated:YES];

    }
    if ( i == 2 ) {
//        NSLog(@"502");
       
            if ([[abmodel status] isEqual: @"0"]) {
                [self showMsg:@"商品上架后才能确认留货"];
                return;
            }
  
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        if (abmodel.status.integerValue == 1) {
            [dict setValue:[AFDownManager MD5String:@"%^&*dongmangoug!@#$setToBePickup"] forKey:@"token"];
            [dict setValue:@"setToBePickup" forKey:@"action"];
            
        }else
        {
            [dict setValue:[AFDownManager MD5String:@"%^&*dongmangoug!@#$setDelivered"] forKey:@"token"];
            [dict setValue:@"setDelivered" forKey:@"action"];
            
        }
        
        [dict setValue:kkUserDict[@"id"] forKey:@"agent_id"];
        [dict setValue:abmodel.id forKey:@"id"];
//        NSLog(@"== %@ == %ld == %@",dict,_section,mode.order_sn);
        [self StartLoading];
        [AFDownManager POST:MakeSureButton parameters:dict success:^(id responseObject) {
            [self StopLoading];
//            NSLog(@"data3= %@",responseObject);
            if ([responseObject[@"code"] intValue] == 0) {
                
                //            [self showMsg:@"确认成功"];
                
                if (abmodel.status.integerValue == 1) {
                    [self downLoadData:@"toBeConfirmed"];
                }else
                {
                    [self downLoadData:@"toBePickup"];
                }
                
              
            }
            else
            {
                [self showMsg:responseObject[@"desc"]];
            }
        } failure:^(NSError *error) {
            [self StopLoading];

//            NSLog(@"error == %@",error);
            [self showMsg:@"网络连接故障"];
        }];

    }
}
#pragma mark 关闭日历或时分界面
- (void)cancelbgViewClick{
    UIWindow *keyWin = [UIApplication sharedApplication].keyWindow;
    
    UIView *bgView = [keyWin viewWithTag:1000];
    UIView *dateHourView = [keyWin viewWithTag:1001];
    [bgView removeFromSuperview];
    [dateHourView removeFromSuperview];
    
    
}
#pragma mark 确认和取消按钮
- (void)ensureOrCancelClick1:(UIButton*)button {

    [self cancelbgViewClick];
}
-(void)ensureOrCancelClick22:(UIButton *)button
{
    [self cancelbgViewClick];

//    UILabel *dateLabel =  (UILabel*)[mLoadView viewWithTag:00];
//    UIWindow *keyWin = [UIApplication sharedApplication].keyWindow;
    
//    UIPickerView *pickView = (UIPickerView*)[[keyWin viewWithTag:1001] viewWithTag:1002];
//    NSLog(@" ======================== %@",pickerViewa.subviews);
    int selectDateIndex = (int)[pickerViewa selectedRowInComponent:0];
    int selectHourIndex = (int)[pickerViewa selectedRowInComponent:1];
 
    NSArray *dateArray = [mDateArray[selectDateIndex] componentsSeparatedByString:@"月"] ;
    NSString *selectStr = nil;
    if ([[dateArray firstObject] integerValue] < mMonth) {
        selectStr = [NSString stringWithFormat:@"%d年%@ %@",mYear+1,mDateArray[selectDateIndex],mHourArray[selectHourIndex]];
//        NSLog(@"============== %@",selectStr);
        
//        [self updateTimeRequest:button timeStr:selectStr];
        [self updateTimeRequest:button timeStr:selectStr intger:button.tag];
        
    }else{
        selectStr = [NSString stringWithFormat:@"%d年%@ %@",mYear,mDateArray[selectDateIndex],mHourArray[selectHourIndex]];
    }
    
//    dateLabel.text = selectStr;
//    NSLog(@"======== %d=== %@ ==== %@",mYear,mDateArray[selectDateIndex],mHourArray[selectHourIndex]);
    
    [self updateTimeRequest:button timeStr:selectStr intger:button.tag];

}

-(void)updateTimeRequest:(UIButton *)sender timeStr:(NSString *)timeStr intger:(NSInteger )intger{
   
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[AFDownManager MD5String:@"%^&*dongmangoug!@#$"] forKey:@"token"];
    [dict setValue:kkUserDict[@"id"] forKey:@"agent_id"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)intger] forKey:@"id"];
    
//    NSLog(@"sender = %@",timeStr);
    NSString *string1 = [timeStr substringWithRange:NSMakeRange(0, 4)];
    NSString *string2 = [timeStr substringWithRange:NSMakeRange(5, 2)];
    NSString *string3 = [timeStr substringWithRange:NSMakeRange(8, 2)];
    NSString *string4 = [timeStr substringWithRange:NSMakeRange(12, 2)];
    NSString *string5 = [timeStr substringWithRange:NSMakeRange(17, 2)];
    //   NSLog(@"%@",[self getCurrentDateString:[NSString stringWithFormat:@"%@-%@-%@ %@:00:00",string1,string2,string3,string5]]);
    [dict setObject:[self getCurrentDateString:[NSString stringWithFormat:@"%@-%@-%@ %@:00:00",string1,string2,string3,string4]] forKey:@"get_starttime"];
    [dict setObject:[self getCurrentDateString:[NSString stringWithFormat:@"%@-%@-%@ %@:00:00",string1,string2,string3,string5]] forKey:@"get_finishtime"];
    [self StartLoading];
//        NSLog(@"url = %@,==%@",yanchangButton,dict);
    [AFDownManager POST:yanchangButton parameters:dict success:^(id responseObject) {
        [self StopLoading];
//        NSLog(@"延长收货时间==== %@ desc === %@",responseObject,responseObject[@"code"]);
        if ([responseObject[@"code"] intValue] == 0) {
            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改成功" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"成功", nil];
            
            [al show];
        }else
        {
            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:responseObject[@"code"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [al show];

        }
        
    } failure:^(NSError *error) {
        [self StopLoading];
        NSLog(@"error == %@",error);
        [self showMsg:@"网络连接故障"];
    }];
    
}
#pragma mark AlterViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (alertView.tag == 900) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://0519-8813239"]];
//        NSLog(@"0519-8813239");
    }
    else
    {
        if (buttonIndex == 1) {
           
            
            OrderABModel *mode = [_datas objectAtIndex:_section];
            if (mode.status.intValue == 1) {
                [self downLoadData:@"toBeConfirmed"];
            }
            if (mode.status.intValue == 2) {
                [self downLoadData:@"toBePickup"];
            }
            
        }
    }
}
//获取时间戳
- (NSString *)getCurrentDateString:(NSString *)timeStr
{
    NSDate *date = [self dateFromString:timeStr];
    
    long long time = date.timeIntervalSince1970;
    
    NSString *str1 = [NSString stringWithFormat:@"%lld", time];
    
    return str1;
    
}
//字符串转NSDate
- (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    
    return [dateFormatter dateFromString:dateString];
    
}
# pragma mark 时间选择器的协议方法

//时间选择器的栏数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}
//为时间选择器添加数据源
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return mDateArray.count;
    }else{
        return mHourArray.count;
    }
    
}
//将数据源显示在view上
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return mDateArray[row] ;
    }else{
        return mHourArray[row];
    }
    
    
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == 0) {
        // NSInteger selectedHourIndex = [pickerView  selectedRowInComponent:1];
        //  NSLog(@"%@",mDateArray[row]);
        if (row<=mSelectedDateIndex) {
            [pickerView selectRow:mSelectedDateIndex inComponent:0 animated:YES];
            [pickerView selectRow:mSelectedhourIndex inComponent:1 animated:YES];
            
        }
    }else{
        NSInteger selectedDateIndex = [pickerView  selectedRowInComponent:0];
        if ((row<mSelectedhourIndex)&&(selectedDateIndex<=mSelectedDateIndex)) {
            [pickerView selectRow:mSelectedhourIndex inComponent:1 animated:YES];
        }
    }
    
}

- (UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:20]];
    }
    // Fill the label text here
    pickerLabel.textColor = [UIColor blackColor];
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
   
    if (component == 0) {
               if (row<mSelectedDateIndex) {
            pickerLabel.textColor = [UIColor lightGrayColor];
        }
    }else{
        NSInteger selectedDateIndex = [pickerView  selectedRowInComponent:0];
        
        if ((row<mSelectedhourIndex)&&(selectedDateIndex<=mSelectedDateIndex)) {
            pickerLabel.textColor = [UIColor lightGrayColor];
        }
    }

    return pickerLabel;
}

#pragma mark 创建时间
- (void)createTimeData{
    [mDateArray removeAllObjects];
    //记录此时此刻的年月日时分
    //记录今天的年月日
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd-HH"];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    //记录预售期的时间
    OrderABModel * model = [_datas  objectAtIndex:_section];
//    NSLog(@"=== %@",model.get_finishtime);
    NSDate *sellTimeDate = [NSDate dateWithTimeIntervalSince1970:[model.get_finishtime doubleValue]];
    NSString *sellDateStr = [dateFormatter stringFromDate:sellTimeDate];
    //判断预售时间是否小于现在
    NSArray *timeArray = nil;
    if ([sellDateStr compare:dateStr options:NSNumericSearch] == NSOrderedAscending) {
        timeArray = [dateStr componentsSeparatedByString:@"-"];
        
    }else{
        timeArray = [sellDateStr componentsSeparatedByString:@"-"];
    }
    mYear = [[timeArray firstObject] intValue];
    mMonth = [[timeArray objectAtIndex:1] intValue];
    mDate = [[timeArray objectAtIndex:2] intValue];
    mHour = [[timeArray lastObject] intValue];
    
    mHourArray = @[@"00 ~ 02点",@"02 ~ 04点",@"04 ~ 06点",@"06 ~ 08点",@"08 ~ 10点",@"10 ~ 12点",@"12 ~ 14点",@"14 ~ 16点",@"16 ~ 18点",@"18 ~ 20点",@"20 ~ 22点",@"22 ~ 00点"];
    mDateArray = [NSMutableArray arrayWithCapacity:10];
    
    for (int i = mMonth; i < 10+mMonth; i++){
        int month = i;
        if (month>12) {
            month-=12;
            
        }
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            for (int j = 1; j < 32; j++) {
                if (j<10) {
                    [mDateArray addObject:[NSString stringWithFormat:@"%02d月%02d日",month,j]];
                }
                else
                {
                    [mDateArray addObject:[NSString stringWithFormat:@"%02d月%d日",month,j]];
                }
            }
        }else{
            if (i != 2) {
                for (int j = 1; j < 31; j++) {
                    if (j<10) {
                        [mDateArray addObject:[NSString stringWithFormat:@"%02d月0%d日",month,j]];
                    }
                    else
                    {
                        [mDateArray addObject:[NSString stringWithFormat:@"%02d月%d日",month,j]];
                    }
                }
            }else{
                if ((mYear-2004)%4 == 0) {
                    for (int j = 1; j < 29; j++) {
                        [mDateArray addObject:[NSString stringWithFormat:@"%02d月0%d日",month,j]];
                    }
                }else{
                    for (int j = 1; j < 28; j++) {
                        [mDateArray addObject:[NSString stringWithFormat:@"%02d月%d日",month,j]];
                    }
                }
            }
            
        }
        
    }
 
    NSString *todayDateStr = [NSString stringWithFormat:@"%d月%d日",mMonth,mDate];
    for (int i = 0; i < mDateArray.count; i++) {
        if ([mDateArray[i] compare:todayDateStr options:NSNumericSearch] == NSOrderedSame) {
            mSelectedDateIndex = i;
        }
        
    }
    for (int i = 0; i < 24; i++) {
        if (mHour == i ) {
            mSelectedhourIndex = i/2;
            
            
        }
    }
    
    
}

//表头
-(void)tableViewHeaderView
{
    _btntitle = [NSArray array];
    _btntitle = @[@"待确认",@"待取货",@"已发货",@"退单"];
    _btnArr = [NSMutableArray array];
    _bigView = [[UIView alloc] initWithFrame:CGRectMake(0,0,  KWidth, KHeight/4)];
    UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(KWidth/6, _bigView.frame.size.height/8, KWidth/3*2, _bigView.frame.size.height/4)];
    UIView *viewImg = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 30, 20)];
    [_bigView addSubview:viewImg];
    UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 1, 20, 20)];
    leftView.image = [UIImage imageNamed:@"SearchButton"];
    [viewImg addSubview:leftView];
    searchField.textColor= [UIColor colorWithRed:0.0/255.0 green:103.0/255.0 blue:155.0/255.0 alpha:1.0];
    searchField.font= [UIFont systemFontOfSize:16] ;
    searchField.leftView = viewImg ;
    searchField.leftViewMode = UITextFieldViewModeAlways;
    searchField.layer.cornerRadius=8.0f;
    searchField.layer.masksToBounds=YES;
    searchField.layer.borderColor=[[UIColor redColor]CGColor];
    searchField.layer.borderWidth= 1.0f;
    searchField.borderStyle=UITextBorderStyleRoundedRect;
    UIColor *color = [UIColor redColor];
    searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"   请输入搜索的订单号" attributes:@{NSForegroundColorAttributeName: color}];
    searchField.textColor = [UIColor redColor];
    searchField.clipsToBounds = YES;
    searchField.layer.cornerRadius = _bigView.frame.size.height/8;
    searchField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    searchField.keyboardType = UIKeyboardTypeEmailAddress;
    searchField.returnKeyType = UIReturnKeyDone;
    [searchField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; // textField的文本发生变化时相应事件
    //设置ReturnKeyType为UIRetuirKeySearch ：
    [searchField setReturnKeyType:UIReturnKeySearch];
    //设置UITextField的delegate为self：
    searchField.delegate=self;
    searchField.tag = 229;
    [_bigView addSubview:searchField];
    UIButton *firstBtn = nil;
    for(int i = 0;i<_btntitle.count;i++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(15+KWidth/4*i, _bigView.frame.size.height/2-10, KWidth/6+5, KWidth/6);
        btn.tag = 220+i;
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitle:[NSString stringWithFormat:@"%@",_btntitle[i]] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        //边框颜色
        [btn.layer setMasksToBounds:YES];
        [btn.layer setCornerRadius:2.0]; //设置矩形四个圆角半径
        //边框宽度
        [btn.layer setBorderWidth:1.0];
        btn.layer.borderColor = [UIColor redColor].CGColor;
        [_bigView addSubview:btn];
        [_btnArr addObject:btn];
        if(i == 0)
        {
            firstBtn = btn;
        }
    }
    [self btnClicked:firstBtn];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, _bigView.frame.size.height-26, 150, 21)];
    titleLabel.textColor = [UIColor redColor];
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.text = @"等待取货:";
    titleLabel.tag = 120;
    UIImageView *imgLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, _bigView.frame.size.height-1, _bigView.frame.size.width, 1)];
    imgLine.backgroundColor = [UIColor lightGrayColor];
    imgLine.alpha = 0.7;
    [self.view addSubview:_bigView];
}
-(void)btnClicked:(UIButton *)sender
{
    for (int i = 0; i<_btnArr.count; i++) {
        
        UIButton *button = _btnArr[i];
        if (sender.tag == button.tag) {
            [button setBackgroundColor:[UIColor redColor]];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
        else
        {
            [button setBackgroundColor:[UIColor whiteColor]];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
    }
    if(sender.tag == 220)
    { self.YesOrNo = 0;
        [self downLoadData:@"toBeConfirmed"];
    }else
        if (sender.tag == 221) {
            self.YesOrNo = 1;
            [self downLoadData:@"toBePickup"];
            
        }else
            if (sender.tag == 222) {
                self.YesOrNo = 2;
                [self downLoadData:@"delivered"];

            }else
                if (sender.tag == 223) {
                    self.YesOrNo = 3;
                    [self downLoadData:@"refund"];
                }
}
//数据请求
-(void)downLoadData:(NSString *)identStr
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if ([identStr  isEqual: @"toBeConfirmed"]) {
        [dict setValue:[AFDownManager MD5String:@"%^&*dongmangoug!@#$toBeConfirmed"] forKey:@"token"];
        _is = identStr;
    }else
    if ([identStr  isEqual: @"toBePickup"]) {
        [dict setValue:[AFDownManager MD5String:@"%^&*dongmangoug!@#$toBePickup"] forKey:@"token"];
        _is = identStr;
    }else
    if ([identStr  isEqual: @"delivered"]) {
        [dict setValue:[AFDownManager MD5String:@"%^&*dongmangoug!@#$delivered"] forKey:@"token"];
    }else if ([identStr  isEqual: @"refund"])
   {
        [dict setValue:[AFDownManager MD5String:@"%^&*dongmangoug!@#$refund"] forKey:@"token"];
    }
    [dict setValue:kkUserDict[@"id"] forKey:@"agent_id"];
    [dict setValue:identStr forKey:@"action"];
    [dict setObject:@"" forKey:@"wd"];
    _tishiLabel.hidden = YES;
       [self StartLoading];
    [AFDownManager POST:OrderDetailOne parameters:dict success:^(id responseObject) {
        [self StopLoading];
        if(_datas.count != 0)
        {
         [_datas removeAllObjects];
        }
       
//        NSLog(@"responseObject == %@",responseObject);
        if ([responseObject[@"data"][@"listData"] count] != 0) {
            _tishiLabel.hidden = YES;
        NSArray *arr = responseObject[@"data"][@"listData"];
        for (NSDictionary *dic in arr) {
            OrderABModel *model = [OrderABModel modelWithDic:dic];
            NSMutableArray * array = [NSMutableArray array];
            if( dic[@"goods"] != [NSNull null])
            {
            for (NSDictionary * childDic in dic[@"goods"]) {
    
                OrderGoodsModel * goodsModel = [[OrderGoodsModel alloc]init];
                
                [goodsModel setValuesForKeysWithDictionary:childDic];
                [array addObject:goodsModel];
            }}
            [model.goodsArray addObjectsFromArray:array];
                [model setValuesForKeysWithDictionary:dic];
            
                [_datas addObject:model];
        }
             }
        else
        {
            _tishiLabel.hidden = NO;
        }
        [_tableView reloadData];
        //取消下拉和上拉的状态
        [_tableView headerEndRefreshing];
    } failure:^(NSError *error) {
        [self StopLoading];
        [self showMsg:@"网络连接故障"];
        //        [_tableView headerEndRefreshing];
    }];
}
#pragma mark textFiled
- (BOOL)textFieldShouldReturn:(UITextField*)theTextField {
    
    [theTextField resignFirstResponder];
    
    if (theTextField.text.length > 0  ) {
        SearchViewController *search = [[SearchViewController alloc] init];
        search.wd = theTextField.text;
        search.is = _is;
        [theTextField resignFirstResponder];
        
        [self.navigationController pushViewController:search animated:YES];
    }
    else
    {
        [self showMsg:@"内容不能为空"];
    }
    return YES;
}
//textField的文本内容发生变化时，处理事件函数
- (void) textFieldDidChange:(UITextField*) TextField{
//    NSLog(@"textFieldDidChange textFieldDidChange");
    if(![TextField.text isEqualToString:@""]) {
        //        delButton.hidden=NO;  // 仿制searchbar后面的小叉叉
    } else{
        //        delButton.hidden=YES;
    }
}
-(void)rightBtn
{
//    NSLog(@"扫描二维码");
    DMErWeiMaViewController *erweima = [[DMErWeiMaViewController alloc] init];
    [self.navigationController pushViewController:erweima animated:YES];
}

-(NSString *)timeStamaps:(NSString *)string
{
    //时间戳转化为时间字符串
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:[string longLongValue]];
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *string1 = [formatter stringFromDate:date];
//    NSLog(@"date1:%@",str);
    return string1;
}

- (void)timerMethod:(NSTimer *)theTimer
{
    if(_datas.count != 0 )
    {
    OrderABModel *model = [self.datas objectAtIndex:_section];
    BOOL timeStart = YES;
    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    NSDateComponents *endTime = [[NSDateComponents alloc] init];    //初始化目标时间...
    NSDate *today = [NSDate date];    //得到当前时间
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateString = [dateFormatter dateFromString:str];
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:model.finish_time.longLongValue];
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//         NSLog(@"==== %f",model.finish_time.longLongValue - [[NSDate date] timeIntervalSince1970]);
        if (model.finish_time.longLongValue - [[NSDate date] timeIntervalSince1970]  <=0) {
            _hview.titleLabel.text = [NSString stringWithFormat:@"订单已完成"];
                    }
        else
        {
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *overdate = [dateFormatter stringFromDate:dateString];
//    NSLog(@"date=%@",date);
//    NSLog(@"today =%@",today);
    static int year;
    static int month;
    static int day;
    static int hour;
    static int minute;
    static int second;
    if(timeStart) {//从NSDate中取出年月日，时分秒，但是只能取一次
        year = [[overdate substringWithRange:NSMakeRange(0, 4)] intValue];
        month = [[overdate substringWithRange:NSMakeRange(5, 2)] intValue];
        day = [[overdate substringWithRange:NSMakeRange(8, 2)] intValue];
        hour = [[overdate substringWithRange:NSMakeRange(11, 2)] intValue];
        minute = [[overdate substringWithRange:NSMakeRange(14, 2)] intValue];
        second = [[overdate substringWithRange:NSMakeRange(17, 2)] intValue];
        timeStart= NO;
    }
    
    [endTime setYear:year];
    [endTime setMonth:month];
    [endTime setDay:day];
    [endTime setHour:hour];
    [endTime setMinute:minute];
    [endTime setSecond:second];
    //    NSDate *overTime = [cal dateFromComponents:endTime]; //把目标时间装载入date
    //用来得到具体的时差，是为了统一成北京时间
    unsigned int unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit| NSDayCalendarUnit| NSHourCalendarUnit| NSMinuteCalendarUnit| NSSecondCalendarUnit;
    NSDateComponents *d = [cal components:unitFlags fromDate:today  toDate:date options:0];
    t = [NSString stringWithFormat:@"%ld", (long)[d day]];
    h = [NSString stringWithFormat:@"%ld", (long)[d hour]];
    fen = [NSString stringWithFormat:@"%ld", (long)[d minute]];
    if([d minute] < 10) {
        fen = [NSString stringWithFormat:@"0%ld",(long)[d minute]];
    }
    miao = [NSString stringWithFormat:@"%ld", (long)[d second]];
    if([d second] < 10) {
        miao = [NSString stringWithFormat:@"0%ld",(long)[d second]];
    }
    if(model.status.intValue == 3 )
    {
    
        [_hview.titleLabel setText:[NSString stringWithFormat:@"等待用户确认:%@天 %@时%@分",t,h,fen]];
        
    }
    if([d second] > 0) {
        //计时尚未结束，do_something
        //        [_longtime setText:[NSString stringWithFormat:@"%@:%@:%@",d,fen,miao]];
    } else if([d second] == 0) {
        //计时结束 do_something
        
    } else{
        //计时器失效
        [theTimer invalidate];
    }
    }
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
